import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '../store'
//import {getToken} from '@/utils/auth'

// create an axios instance
const service = axios.create({
    //基础的根路径
    baseURL: "http://localhost:8888", 
    //超时时间
  timeout: 5000 
})

// request interceptor 拦截器
service.interceptors.request.use(
  config => {
    // 在请求头提供token
    const token = store.getters.token || window.sessionStorage.getItem('token')
    if (token) { 
        //每次请求都会携带token
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应的拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // 如果返回码不是200,表示我们的代码肯定有问题
     if (res.code !== 200) {
       Message({
         message: res.message || 'Error',
         type: 'error',
        duration: 2 * 1000
       })

    //未登录的校验
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }

    //返回错误的消息
       return Promise.reject(new Error(res.message || 'Error'))
     } else {
        //这里是成功,则返回内容
      return res.data
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
